package thread;

class MyBlockingQueue {
    private int[] arr;
    private int head = 0;
    private int tail = 0;
    //有效值的数量
    private int size = 0;
    public MyBlockingQueue(int capacity) {
        arr = new int[capacity];
    }
    public void put(int elem) throws InterruptedException {
        synchronized (this) {
            //阻塞操作
            while (size >= arr.length) {
                //队列元素满了，需要阻塞
                this.wait();
            }
            arr[tail] = elem;
            tail++;
            size++;
            this.notify();
            if (tail >= arr.length) {
                tail = 0;
            }
        }
    }
    public int take() throws InterruptedException {
        synchronized (this) {
            //阻塞操作
            while (size == 0) {
                //队列元素为空，需要阻塞
                this.wait();
            }
            int ret = arr[head];
            head++;
            size--;
            this.notify();
            if (head >= arr.length) {
                head = 0;
            }
            return ret;
        }
    }
}
public class Demo24 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(4);
        Thread producer = new Thread(() -> {
            int n = 0;
            while (true) {
                try {
                    queue.put(n);
                    System.out.println("生产了"+n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();
        Thread consumer = new Thread(() -> {
            while (true) {
                try {
                    int n = queue.take();
                    System.out.println("消费了"+n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        consumer.start();
    }
}
